<template>
  <view class="dynamic-form">
    <uni-forms
      :value="model"
      @submit="onSubmit"
      :rules="formRules"
      validate-trigger="submit"
      v-if="Object.keys(model).length > 0"
      ref="form"
    >
      <view v-for="control in formControls" :key="control.columnName">
        <DynamicFormControl :control="control" v-model="model[control.columnName]" />
        <!-- <view>{{ control.columnName }}:{{ model[control.columnName] }}</view> -->
      </view>
      <button v-if="!disabled" class="dynamic-form__submit-btn" @click="submit">提交表单</button>
    </uni-forms>
  </view>
</template>

<script>
import UniForms from '../uni-forms/uni-forms'
import DynamicFormControl from './controls'
import uuidCreator from './uuidCreator'
import rulesCreator from './rulesCreator'
export default {
  props: {
    formSchema: {
      type: Object,
      default: () => ({}),
    },
    open_id: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: {
    UniForms,
    DynamicFormControl,
  },
  data() {
    return {
      name: '',
      model: {},
    }
  },
  watch: {
    formControls: {
      handler(val) {
        //console.log('handler变化了', val)
        const createDefaultValue = (columnFormat, value, defaultValue) => {
          console.log(`${columnFormat}:${value}`)
          return {
            text: value || defaultValue || '',
            textarea: value || defaultValue || '',
            combo: value || defaultValue || '',
            date: value || defaultValue || '',
            check: typeof value === 'string' ? value.split(',') : defaultValue || [],
            radio: value || defaultValue || '',
            attachment: Array.isArray(value)
              ? value.map((att) => {
                  return {
                    name: att.name,
                    extname: att.name.split('.')[1],
                    url: att.url,
                  }
                })
              : defaultValue || [],
            image: value || defaultValue || [],
          }[columnFormat]
        }
        this.model = Object.fromEntries(
          val.map((column) => [
            column.columnName,
            createDefaultValue(column.columnFormat, column.values || column.attachment, column.defaultValue),
          ])
        )
      },
      // immediate: true,
    },
  },
  computed: {
    formControls() {
      //附件上传需要的guid
      return this.formSchema.columns
        ? this.formSchema.columns.map((col) => {
            return {
              ...col,
              guid: col.columnFormat === 'attachment' ? uuidCreator() : undefined,
            }
          })
        : []
    },
    formRules() {
      return (
        this.formSchema.columns &&
        Object.fromEntries(
          this.formSchema.columns.map((column) => [
            column.columnName,
            { rules: rulesCreator(column) || [], label: column.columnDesc },
          ])
        )
      )
    },
  },

  methods: {
    onSubmit() {},
    submit() {
      console.log(this.model)
      console.log(this.formRules)
      this.$refs.form
        .submit()
        .then((res) => {
          //console.log(res)
          this.formControls.forEach((control) => {
            if (control.columnFormat === 'attachment' && res.hasOwnProperty(control.columnName)) {
              res[control.columnName] = res[control.columnName].length > 0 ? control.guid : ''
            }
            if (control.columnFormat === 'check' && res.hasOwnProperty(control.columnName)) {
              res[control.columnName] = res[control.columnName].join(',')
            }
          })
          this.$emit('submit', res)
          // 成功返回，res 为表单数据
          // 其他逻辑处理
          // ...
        })
        .catch((err) => {
          console.error(err)
          // 表单校验验失败，err 为具体错误信息
          // 其他逻辑处理
          // ...
        })
    },
  },
}
</script>

<style lang="scss">
.dynamic-form {
  //border: 1px solid red;
  padding: 24rpx;
  &__submit-btn {
    background-color: #0080ff;
    color: #ffffff;
  }
}
</style>
